package net.ankao.job.configuration;

import net.ankao.job.common.Constant;
import net.ankao.job.job.ClientJob;
import net.ankao.job.job.HeartbeatJob;
import net.ankao.job.job.StatisticsJob;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * @author LILU
 * @date 2024-11-28 9:13
 */
@Configuration
public class QuartzAutoConfiguration {


    @Bean
    public Scheduler scheduler() throws SchedulerException {
        return StdSchedulerFactory.getDefaultScheduler();
    }

    @Bean
    public JobDetail heartbeatJob() {
        return JobBuilder.newJob(HeartbeatJob.class)
                .withIdentity("heartbeatJob", Constant.SERVER_GROUP)
                .storeDurably()
                .build();
    }

    @Bean
    public JobDetail statisticsJob() {
        return JobBuilder.newJob(StatisticsJob.class)
                .withIdentity("statisticsJob", Constant.SERVER_GROUP)
                .storeDurably()
                .build();
    }

    @Bean
    public Trigger heartbeatTrigger(JobDetail heartbeatJob) {
        return TriggerBuilder.newTrigger()
                .forJob(heartbeatJob)  // 引用已定义的JobDetail Bean
                .withIdentity("heartbeatJobTrigger", Constant.SERVER_GROUP)
                .withSchedule(CronScheduleBuilder.cronSchedule("0/30 * * * * ?"))
                .build();
    }

    @Bean
    public Trigger statisticsTrigger(JobDetail statisticsJob) {
        return TriggerBuilder.newTrigger()
                .forJob(statisticsJob)  // 引用已定义的JobDetail Bean
                .withIdentity("statisticsJobTrigger", Constant.SERVER_GROUP)
                .withSchedule(CronScheduleBuilder.cronSchedule("0 0/5 * * * ?"))
                .build();
    }

    // 动态添加任务
    public void addJob(Scheduler scheduler, String jobName, String groupName, String cronExpression, Map<String, Object> parameter) throws SchedulerException {
        JobDataMap jobDataMap = new JobDataMap();
        if (parameter != null) {
            parameter.forEach((k, v) -> {
                jobDataMap.put(k, v);
            });
        }
        JobDetail jobDetail = JobBuilder.newJob(ClientJob.class)
                .withIdentity(jobName, groupName)
                .storeDurably()
                .setJobData(jobDataMap)
                .build();


        CronTrigger trigger = TriggerBuilder.newTrigger()
                .forJob(jobDetail)
                .withIdentity(jobName + "Trigger", groupName)
                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
                .build();

        scheduler.scheduleJob(jobDetail, trigger);
    }

    // 动态删除任务
    public void deleteJob(Scheduler scheduler, String jobName, String groupName) throws SchedulerException {
        JobKey jobKey = new JobKey(jobName, groupName);
        if (scheduler.checkExists(jobKey)) {
            scheduler.deleteJob(jobKey);
        }
    }

    // 动态修改任务
    public void rescheduleJob(Scheduler scheduler, String jobName, String groupName, String newCronExpression, Map<String, Object> parameter) throws SchedulerException {
        // 获取当前的触发器
        TriggerKey triggerKey = new TriggerKey(jobName + "Trigger", groupName);
        CronTrigger currentTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);

        if (currentTrigger == null) {
            throw new SchedulerException("Trigger not found: " + triggerKey);
        }

        // 创建新的CronTrigger
        CronTrigger newTrigger = TriggerBuilder.newTrigger()
                .withIdentity(triggerKey)
                .withSchedule(CronScheduleBuilder.cronSchedule(newCronExpression))
                .build();

        // 获取当前的任务
        JobKey jobKey = new JobKey(jobName, groupName);
        JobDetail currentJob = scheduler.getJobDetail(jobKey);

        if (currentJob == null) {
            throw new SchedulerException("Job not found: " + jobKey);
        }

        JobDataMap jobDataMap = new JobDataMap();
        if (parameter != null) {
            parameter.forEach((k, v) -> {
                jobDataMap.put(k, v);
            });
        }

        // 重新构建JobDetail
        JobDetail newJob = JobBuilder.newJob(currentJob.getJobClass())
                .withIdentity(jobKey)
                .setJobData(jobDataMap)
                .build();

        // 删除旧的任务
        scheduler.deleteJob(jobKey);
        // 添加新的任务和触发器
        scheduler.scheduleJob(newJob, newTrigger);
    }
}
